#import "Configuration.h"

@implementation Configuration

- (id)initWithView: (UIPreferencesTable *)t 
{
	int i, j;

	[self load];
		
	tPrefs = t;
	
	[tPrefs setDataSource:self];
  	[tPrefs setDelegate:self];
	
	cRecallTime = [[UISegmentedControl alloc] initWithFrame:CGRectMake(170.0f, 5.0f, 120.0f, 55.0f) ];
	[cRecallTime insertSegment:0 withTitle:@"OFF" animated:NO];
	[cRecallTime insertSegment:1 withTitle:@"1" animated:NO];
	[cRecallTime insertSegment:2 withTitle:@"10" animated:NO];
	[cRecallTime selectSegment:recallTime];
	
	for(i = 0; i < C_GROUPS; i++) {
		for(j = 0; j < C_CELLS; j++) {
			cl[i][j] = nil;	
		}
		gcl[i] = nil;
	}
	
	[tPrefs reloadData];
	
	return self;
}

- (void) dealloc
{
	int i, j;

	[self save];

	[cRecallTime release];

	for(i = 0; i < C_GROUPS; i++) {
		for(j = 0; j < C_CELLS; j++) {
			if(cl[i][j] != nil) [cl[i][j] release];	
		}
		if(gcl[i] != nil) [gcl[i] release];
	}
	
	[super dealloc];
}

- (void) load
{
	FILE *f;
  
  	f = fopen(CONF_FILE, "rt");
  	if(f) {
  		fscanf(f, "recallTime: %d\n", &recallTime);

		fclose(f);
  	} else {
  		// default params
  		recallTime = 0;
  	}
}

- (void) save 
{
	FILE *f;
 
 	// get all params from input elements
 	
 	recallTime = [cRecallTime selectedSegment];
  
  	f = fopen(CONF_FILE, "wt");
  	if(f) {
  		fprintf(f, "recallTime: %d\n", recallTime);  		
  		
		fclose(f);
  	} else {
  		NSLog(@"Unable to write the configuration file.");	
  	}
}

/*
	Preferences proto
*/
- (int)numberOfGroupsInPreferencesTable:(UIPreferencesTable *)t 
{
	return 1;
}
    
- (int)preferencesTable:(UIPreferencesTable *)t 
	numberOfRowsInGroup:(int)g
{
	return 1;
}

- (UIPreferencesTableCell *)preferencesTable:(UIPreferencesTable *)t
    cellForGroup:(int)g 
{
	if(gcl[g] == nil) { 
		gcl[g] = [[UIPreferencesTextTableCell alloc] initWithFrame:CGRectMake(0, 0, 320, 30)];
	
		switch(g) {
			case(0): {
    			[gcl[g] setTitle:NSLocalizedString(@"Control Params", @"iControlParams")];
    			break;
    		}
    	}
    }
    return gcl[g];
}
 
- (float)preferencesTable:(UIPreferencesTable *)t
    heightForRow:(int)r
    inGroup:(int)g
    withProposedHeight:(float)p
{
    if (r == -1) return 40.0f;
    else return 55.0f;
}

- (BOOL)preferencesTable:(UIPreferencesTable *)t
    isLabelGroup:(int)g 
{
    return NO; 
}

- (UIPreferencesTableCell *)preferencesTable:(UIPreferencesTable *)t
    cellForRow:(int)r
    inGroup:(int)g 
{
	if(cl[g][r] == nil) {	
		UIPreferencesTableCell *c = [[UIPreferencesTableCell alloc] init];
	 
		switch(g) {
			case(0): {
				// Main group
			
				switch(r) {
					case(0): {
						// Recall period config
						[c setTitle:NSLocalizedString(@"Recall time", @"iRecallTime")];
      					[c addSubview:cRecallTime];
					}
				} 
				break;
			}
		}; 
		cl[g][r] = c;
	}
	return cl[g][r];
}


@end

